
# Build and load C function
setwd("/Users/ben/Documents/Papers/Artificial waterbodies") #set the working directory
system("R CMD SHLIB Pacala_pairwise.c")
dyn.load("Pacala_pairwise.so")

#####-------------------Functions-----------------#####

#The tradeoff between growth and dispersal
tradeoff<-function(gene.growth){
	3-gene.growth	
}

#creates a matrix of Individuals, opportunities and distances
#	Pairwise computation is reduced by the pacala grid
#	Calls a compiled C function - "localiser"
localiser<-function(srcmatrix, potmatrix, space.X, space.Y, grid.size){
	cs<-grid.size
	ps=length(srcmatrix[,1])
	os=length(potmatrix[,1])
	opps.per.cell<-os/((space.X*space.Y)/cs^2)
	if (opps.per.cell<1){
		print("Error in localiser: opps.per.cell<1")
		return(NULL)	
	}
	is<-rep(0, os*ps)
	ID<-is
	dis<-as.double(is)
	n<-0 # variable to take length of resulting vectors
	inds<-.C("localiser", iX=as.double(srcmatrix[,1]), iY=as.double(srcmatrix[,2]),
			oX=as.double(potmatrix[,1]), oY=as.double(potmatrix[,2]), cellsize=as.double(cs),
			popsize=as.integer(ps), oppsize=as.integer(os), 
			spaceX=as.integer(space.X), spaceY=as.integer(space.Y), 
			indexes=as.integer(is), indID=as.integer(ID), 
			dists=dis, L=as.integer(n))
	inds<-cbind(inds$indID+1, inds$indexes+1, inds$dists)[1:inds$L,]
	colnames(inds)<-c("Ind", "Opp", "Dist")
	inds
}

### Test the function ###
sX<-20  #Dimensions of space
sY<-sX
n<-300 #initial pop/opp size
mat<-cbind(runif(n,0,sX), runif(n, 0, sY))
gs<-5

localiser(mat, mat, sX, sY, gs)
